package com.riwon.im.common.config;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.riwon.im.common.constant.UserConstant;
import com.riwon.im.pojo.User;
import com.riwon.im.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author wpy
 * @date 2018/5/9 17:28
 */
@Configuration
public class WebSocketConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketConfig.class);

    @Resource
    private ApplicationProperties properties;
    @Resource
    private IUserService userServiceimpl;

    @Bean
    public SocketIOServer socketIOServer() {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setHostname(properties.getWebSocketHost());
        config.setPort(properties.getWebSocketPort());
        //身份验证
        config.setAuthorizationListener(this::isAuthorized);
        return new SocketIOServer(config);
    }

    /**
     * APP 端是否考虑身份认证
     * @param data
     * @return
     */
    private boolean isAuthorized(HandshakeData data){
        /*try {
            String userType = data.getSingleUrlParam("userType");
            String token = data.getSingleUrlParam("token");
            if(NumberUtils.isCreatable(userType)){
                if(NumberUtils.createInteger(userType).equals(Type.USER.getCode())){
                    String resultStr = HttpClientUtils.get(properties.getRjGetUserUrl()+"?token="+token);
                    JSONObject result = JSON.parseObject(resultStr);
                    final String code = "code";
                    final int JSON_NEED_LOGIN = 700;
                    if(result.get(code).equals(JSON_NEED_LOGIN)){
                        return false;
                    }
                }
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            return false;
        }*/
        return true;
    }


    @Resource
    private IUserService userServiceImpl;

    @Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
        socketServer.start();
        User user = new User();
        user.setState(UserConstant.State.OFFLINE.getCode());
        userServiceImpl.update(user,new EntityWrapper<>());
        return new SpringAnnotationScanner(socketServer);
    }

}
